import os
import json
import traceback

from flask import Flask
from flask import request, render_template, make_response, jsonify
from flask_cors import CORS
from werkzeug.exceptions import HTTPException

app = Flask(__name__, template_folder="html")
app.config['DEBUG'] = True

CORS(app, resources={
    r"/api/*": {
        "origins": ["http://www.websecurity.com"],
        "methods": ["GET", "POST", "DELETE"],
        "allow_headers": ["Content-Type"],
        "expose_headers": ["Content-Length"],
        "supports_credentials": True,
        "max_age": 3600
    }
})

# 404错误处理
@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html'), 404

# 500错误处理
@app.errorhandler(500)
def internal_error(error):
    # 获取错误的堆栈跟踪信息
    error_traceback = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
    
    return render_template('500.html', error=error, error_traceback=error_traceback), 500

# 处理所有HTTP异常
@app.errorhandler(HTTPException)
def handle_http_exception(error):
    return render_template('error.html', error=error), error.code

# 处理所有未捕获的异常
@app.errorhandler(Exception)
def handle_exception(error):
    # 获取错误的堆栈跟踪信息
    error_traceback = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
    
    return render_template('500.html', error=error, error_traceback=error_traceback), 500

@app.route("/")
def default():
    return render_template("index.html")

@app.route("/<page_name>.html")
def page(page_name):
    return render_template(f"{page_name}.html")

@app.route('/jsonp/data')
def get_data():
    callback = request.args.get('callback')
    
    data = {
        'name': '张三',
        'age': 25,
        'text': '大理大学冬天真冷'
    }

    json_data = json.dumps(data, ensure_ascii=False)
    # 修改下行代码
    response_data = '替换此处的代码';
    response = make_response(response_data)
    response.headers['Content-Type'] = 'application/javascript; charset=utf-8'

    print("============= response =============")
    print(bytes.decode(response.data))
    print("============= response =============")
    
    return response

@app.route('/api/data', methods=['GET', 'POST', 'PUT'])
def handle_data():
    if request.method == 'GET':
        return jsonify({"message": "GET 数据获取成功"})
    elif request.method == 'POST':
        data = request.json
        return jsonify({"message": "POST 数据提交成功", "data": data})
    elif request.method == 'PUT':
        data = request.json
        return jsonify({"message": "PUT 数据更新成功", "data": data})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8002, debug=True)